#include "CScene.h"
#include "globals.h"

CScene::CScene (void)
{
	m_bIsLoad = false;
	//m_pLight = NULL;
}

CScene::~CScene (void)
{
	//delete m_pLight;
}

void CScene::Init ()
{
	glClearColor (0.0, 0.0, 0.0, 0.0);

	glEnable (GL_DEPTH_TEST);
	
	glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
	//m_terrain.show(false);

	//m_pLight = new LightSource(GL_LIGHT0);
	//m_pLight->show();
	//m_pLight->showAxes(false);
	//m_pLight->setPosition(0, 1, 1);

	//m_FT.pushChild(m_pLight);
	m_FT.showAxes();

	//m_pLight->setPosition(0, 3, 0);

	//m_pLight->pushChild(&m_camera);
	m_FT.pushChild(&m_HNode);
	m_HNode.setPosition(0, 5, 5);
	m_HNode.pushChild(&m_VNode);
	m_VNode.pushChild(&m_camera);
	m_VNode.pitch(-45.0f);

	m_root.pushChild( &m_terrain);
	m_root.pushChild( &m_FT);

	m_terrain.loadTerrain(L"test2.trn");//m_terrain.saveTerrain(L"test.trn");
	m_FT.putOnTerrain(&m_terrain, Vector3::ZERO);

	m_controller.Init (&m_FT, &m_camera, &m_HNode, &m_VNode, 0, m_wWndWidth, m_wWndHeight);

	glEnable(GL_COLOR_MATERIAL);
	glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
}

void CScene::Resize (WORD width, WORD height)
{
	if (height == 0)
		height = 1;

	m_wWndWidth  = width;
	m_wWndHeight = height;

	glViewport (0, 0, m_wWndWidth, m_wWndHeight);

	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();

	gluPerspective (60.0, (GLdouble)width / (GLdouble)height, 0.1, 10000.0);
}

void CScene::Render()
{
	Vector3 pos;
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	float m[16];

	glColor3f (1.0, 0.0, 0.0);
	m_controller.Render ();
	
	glMatrixMode (GL_MODELVIEW);
	glLoadIdentity ();

	m_camera.look(Viewport(0, 0, m_wWndWidth, m_wWndHeight));

	//gluLookAt(-10, 10, 10, 0, 3, 3, 0, 1, 0);

	glGetFloatv(GL_MODELVIEW_MATRIX, m);

	m_root.render ();

	pos = m_camera.getWorldPosition();

	//g_msg.begin (Viewport (0, 0, m_wWndWidth, m_wWndHeight));
	//g_msg.printf(g_fontID, 10, 30, 1, "cam_pos = (%f, %f, %f)", pos.x, pos.y, pos.z);
	//g_msg.end ();
}

void CScene::LoadModel (const wstring& szFileName)
{
	m_terrain.show(false);
	//m_terrain.loadOBJ (szFileName);
	//m_terrain.saveTerrain(L"test2.trn");
	//m_terrain.showAxes ();
	m_terrain.show(true);
	//m_terrain.showNormal();
	m_terrain.enableLighting(true);
	m_terrain.setRenderMode(DKGL::RM_POLYGON);
	m_terrain.loadTerrain(L"test2.trn");//m_terrain.saveTerrain(L"test.trn");

	m_FT.putOnTerrain(&m_terrain, Vector3::ZERO);

	Vector3 size = m_terrain.getSize();
	
	m_controller.Init (&m_FT, &m_camera, &m_HNode, &m_VNode, size.x, m_wWndWidth, m_wWndHeight);
}
